package com.hangsu.train.components.configuration;

import com.hangsu.train.core.keygen.KeyGenerate;
import com.hangsu.train.core.keygen.SnowflakeKeyGenerate;
import jakarta.annotation.Resource;
import org.apache.ibatis.logging.slf4j.Slf4jImpl;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;


/**
 * @author lyy
 */
@Configuration
@MapperScan(basePackages = "com.hangsu.train.components.dao")
public class MybatisConfigration {

    private DataSource dataSource;

    @Bean
    KeyGenerate getKeyGenerate() {
        return new SnowflakeKeyGenerate();
    }

    @Resource
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public static final String MAPPERLOCATION = "classpath*:mybatis/*.xml";

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);

        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setLogImpl(Slf4jImpl.class);
        configuration.setMapUnderscoreToCamelCase(true);
        factoryBean.setConfiguration(configuration);

        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPERLOCATION));
        return factoryBean.getObject();
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate() throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory());
    }

}